package com.leyou.common.advice;


import com.leyou.common.exception.LyException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Slf4j
@Aspect//AOP把当前类标识为一个切面供容器读取
@Component//把普通pojo实例化到spring容器中，相当于配置文件中的
public class CommonLogAdvice {

    @Around("within(@org.springframework.stereotype.Service *) " +
            "|| (within(com.baomidou.mybatisplus.extension.service.IService+) " +
            "&& ! execution(* com.baomidou.mybatisplus.extension.service.IService.query())" +
            "&& ! execution(* com.baomidou.mybatisplus.extension.service.IService.update())" +
            ")")
    public Object handleExceptionLog(ProceedingJoinPoint jp)throws Throwable{
        try {
//记录方法进入日志
            log.debug("{}方法准备调用，参数：{}", jp.getSignature(),
                    Arrays.toString(jp.getArgs()));
            long a = System.currentTimeMillis();
//        调用切点方法
            Object result = jp.proceed();
            log.debug("{}方法调用成功，执行耗时{}",jp.getSignature(),
                    System.currentTimeMillis()-a);
//        返回结果
            return result;
        } catch (Throwable throwable) {

            log.error("{}方法执行失败，原因是{}", jp.getSignature(),
                    throwable.getMessage(), throwable);
//            判断异常是否为LyException自动有异常
            if(throwable instanceof LyException){
                throw throwable;
            }else {
                throw new LyException(500, throwable);
            }
        }


    }





}
